package com.swpu.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swpu.seckill.exception.GlobalException;
import com.swpu.seckill.mapper.UserMapper;
import com.swpu.seckill.pojo.User;
import com.swpu.seckill.service.IUserService;
import com.swpu.seckill.util.CookieUtil;
import com.swpu.seckill.util.MD5Util;
import com.swpu.seckill.util.UUIDUtil;
import com.swpu.seckill.vo.LoginVo;
import com.swpu.seckill.vo.RespBean;
import com.swpu.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * InnoDB free: 10240 kB 服务实现类
 * </p>
 *
 * @author 陈婷
 * @since 2022-03-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired(required=false)
    private UserMapper userMapper;
    @Autowired(required=false)
    private RedisTemplate redisTemplate;
    /**
     *登录接口的实现
     * @param loginVo
     * @param request
     * @param response
     * @return
     */
    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        //根据手机号获取用户
        User user = userMapper.selectById(mobile);
        if(null == user){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        //判断密码是否正确
        if(!(MD5Util.formPassToDBPass(password,user.getSlat())).equals(user.getPasword())){
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        //生成cookie
        String ticket = UUIDUtil.uuid();
//        request.getSession().setAttribute(ticket,user);
        redisTemplate.opsForValue().set("user:"+ticket,user);
        CookieUtil.setCookie(request,response,"userTicket",ticket);
        return RespBean.sucess();
    }

    /**
     * 根据cookie获取用户信息
     * @param userTicket
     * @return
     */
    @Override
    public User getUserByCookie(String userTicket,HttpServletRequest request,HttpServletResponse response) {
        if(StringUtils.isEmpty(userTicket)){
            return  null;
        }
        User user = (User)redisTemplate.opsForValue().get("user:" + userTicket);
        if(null != user){
        CookieUtil.setCookie(request,response,"userTicket",userTicket);
        }
        return user;
    }
}
